package com.ccx.coachsite.ui.tutorial;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.ccx.coachsite.R;
import com.ccx.coachsite.bus.TutorialInfo;
import com.ccx.coachsite.bus.TutorialPageInfo;
import com.ccx.coachsite.bus.TutorialProvider;
import com.ccx.coachsite.ui.AppBaseView;
import com.ccx.coachsite.ui.customview.ViewPager;

public class TutorialList extends AppBaseView {

	private List<TutorialPageInfo> tutorials;

	private ViewPager androidContent, iphoneContent, wpContent;
	private TutorialPageBar androidPage, iphonePage, wpPage;
	private RadioButton rbAndroid, rbIphone, rbWP;
	private View androidView, iPhoneView, wpView;
	private View listView, searchView;
	private Button btnSearch, btnDoSearch;
	private InputMethodManager imm;
	private EditText editKeyword;
	private ListView resultList;

	public TutorialList(Context context) {
		super(context);
		addView(R.layout.tutorial_page_view);
		addView(R.layout.tutorial_search_page);

		listView = findViewById(R.id.ll_tutorial_page_view);
		searchView = findViewById(R.id.ll_tutorial_search);

		rbAndroid = (RadioButton) findViewById(R.id.tutorial_rb_android);
		rbIphone = (RadioButton) findViewById(R.id.tutorial_rb_iphone);
		rbWP = (RadioButton) findViewById(R.id.tutorial_rb_wp);

		androidView = findViewById(R.id.tutorial_android_page);
		iPhoneView = findViewById(R.id.tutorial_iphone_page);
		wpView = findViewById(R.id.tutorial_wp_page);

		androidContent = (ViewPager) findViewById(R.id.tutorial_android_page_content);
		androidPage = (TutorialPageBar) findViewById(R.id.tutorial_android_page_control);
		androidContent.setTab(androidPage);

		iphoneContent = (ViewPager) findViewById(R.id.tutorial_iphone_page_content);
		iphonePage = (TutorialPageBar) findViewById(R.id.tutorial_iphone_page_control);
		iphoneContent.setTab(iphonePage);

		wpContent = (ViewPager) findViewById(R.id.tutorial_wp_page_content);
		wpPage = (TutorialPageBar) findViewById(R.id.tutorial_wp_page_control);
		wpContent.setTab(wpPage);

		findViewById(R.id.ll_tutorial_page_view).findViewById(
				R.id.login_btn_return).setVisibility(INVISIBLE);
		((TextView) findViewById(R.id.login_top_title))
				.setText(R.string.tutorial_topic);
		rbAndroid.setOnCheckedChangeListener(rbAndroidCheckedListener);
		rbIphone.setOnCheckedChangeListener(rbIphoneCheckedListener);
		rbWP.setOnCheckedChangeListener(rbWPCheckedListener);

		btnSearch = (Button) listView.findViewById(R.id.login_top_right);
		btnSearch.setBackgroundResource(R.drawable.tou_butt_search);
		btnSearch.setVisibility(VISIBLE);
		// btnSearch.setText("搜索");
		btnSearch.setOnClickListener(btnSearchClickListener);

		resultList = (ListView) findViewById(R.id.tutorial_search_result_list);
		resultList.setOnItemClickListener(resultItemClickListener);
		findViewById(R.id.tutorial_search_loading).setVisibility(INVISIBLE);

		imm = (InputMethodManager) getContext().getSystemService(
				Context.INPUT_METHOD_SERVICE);

		refreshData();
	}

	@Override
	protected boolean onLoadData() {
		tutorials = TutorialProvider.getInstance().getTutorials();
		if (tutorials != null)
			return true;
		return false;
	}

	@Override
	protected void onRefreshDataSuccess() {
		super.onRefreshDataSuccess();
		List<TutorialPageDataLoader> androidLoaders = new ArrayList<TutorialPageDataLoader>();
		List<TutorialPageDataLoader> iphoneLoaders = new ArrayList<TutorialPageDataLoader>();
		List<TutorialPageDataLoader> wpLoaders = new ArrayList<TutorialPageDataLoader>();
		for (TutorialPageInfo tutorialPageInfo : tutorials) {
			View view = inflate(getContext(), R.layout.tutorial_main, null);
			if (tutorialPageInfo.getPageType() == 1) {
				androidContent.addView(view);
				androidLoaders.add(new TutorialPageDataLoader(view,
						tutorialPageInfo));
			} else if (tutorialPageInfo.getPageType() == 2) {
				iphoneContent.addView(view);
				iphoneLoaders.add(new TutorialPageDataLoader(view,
						tutorialPageInfo));
			} else {
				wpContent.addView(view);
				wpLoaders
						.add(new TutorialPageDataLoader(view, tutorialPageInfo));
			}
		}
		androidPage.setTutorialPageLoaders(androidLoaders);
		iphonePage.setTutorialPageLoaders(iphoneLoaders);
		wpPage.setTutorialPageLoaders(wpLoaders);
		androidContent.setToScreen(0);
		iphoneContent.setToScreen(0);
		wpContent.setToScreen(0);
		switchView(R.id.ll_tutorial_page_view);
	}

	@Override
	public boolean goBack() {
		if (getCurrentView().equals(searchView)) {
			switchView(listView);
			return true;
		}
		return super.goBack();
	}

	private void onSearchSuccess(List<TutorialInfo> result) {
		btnDoSearch.setEnabled(true);
		findViewById(R.id.tutorial_search_loading).setVisibility(INVISIBLE);
		if (result.size() > 0) {
			findViewById(R.id.tutorial_search_result_list).setVisibility(
					VISIBLE);
			findViewById(R.id.tutorial_no_search_result).setVisibility(
					INVISIBLE);
		} else {
			findViewById(R.id.tutorial_search_result_list).setVisibility(
					INVISIBLE);
			findViewById(R.id.tutorial_no_search_result).setVisibility(VISIBLE);
		}
		SearchResultAdapter adapter = new SearchResultAdapter(result);
		resultList.setAdapter(adapter);
	}

	private void onSearchFail() {
		btnDoSearch.setEnabled(true);
		findViewById(R.id.tutorial_search_loading).setVisibility(INVISIBLE);
		if (TextUtils.isEmpty(TutorialProvider.getInstance()
				.getLastErrorMessage())) {
			Toast.makeText(getContext(), "对不起，搜索失败，请重试", Toast.LENGTH_SHORT)
					.show();
		} else {
			Toast.makeText(getContext(),
					TutorialProvider.getInstance().getLastErrorMessage(),
					Toast.LENGTH_SHORT).show();
		}
	}

	OnCheckedChangeListener rbAndroidCheckedListener = new OnCheckedChangeListener() {

		@Override
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {
			if (isChecked) {
				androidView.setVisibility(VISIBLE);
				iPhoneView.setVisibility(INVISIBLE);
				wpView.setVisibility(INVISIBLE);
			}
		}
	};

	OnCheckedChangeListener rbIphoneCheckedListener = new OnCheckedChangeListener() {

		@Override
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {
			if (isChecked) {
				androidView.setVisibility(INVISIBLE);
				iPhoneView.setVisibility(VISIBLE);
				wpView.setVisibility(INVISIBLE);
			}
		}
	};

	OnCheckedChangeListener rbWPCheckedListener = new OnCheckedChangeListener() {

		@Override
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {
			if (isChecked) {
				androidView.setVisibility(INVISIBLE);
				iPhoneView.setVisibility(INVISIBLE);
				wpView.setVisibility(VISIBLE);
			}
		}
	};

	OnClickListener btnSearchClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			((TextView) searchView.findViewById(R.id.login_top_title))
					.setText("搜索");
			editKeyword = (EditText) searchView
					.findViewById(R.id.tutorial_search_keyword);
			btnDoSearch = (Button) searchView
					.findViewById(R.id.tutorial_search_button);
			switchView(searchView);
			ImageButton btnReturn = (ImageButton) searchView
					.findViewById(R.id.login_btn_return);
			btnReturn.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					imm.hideSoftInputFromWindow(editKeyword.getWindowToken(), 0);
					switchView(listView);
				}
			});
			btnDoSearch.setOnClickListener(btnDoSearchcliClickListener);
		}
	};

	OnClickListener btnDoSearchcliClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (TextUtils.isEmpty(editKeyword.getText().toString().trim())) {
				Toast.makeText(getContext(), "请输入关键字", Toast.LENGTH_SHORT)
						.show();
				return;
			}
			imm.hideSoftInputFromWindow(editKeyword.getWindowToken(), 0);
			findViewById(R.id.tutorial_search_loading).setVisibility(VISIBLE);
			findViewById(R.id.tutorial_search_result_list).setVisibility(
					INVISIBLE);
			findViewById(R.id.tutorial_no_search_result).setVisibility(
					INVISIBLE);
			btnDoSearch.setEnabled(false);
			SearchTask task = new SearchTask();
			task.execute(editKeyword.getText().toString().trim());
		}
	};

	OnItemClickListener resultItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			SearchResultAdapter adapter = (SearchResultAdapter) parent
					.getAdapter();
			TutorialInfo tutorial = (TutorialInfo) adapter.getItem(position);
			Intent intent = new Intent(getContext(),
					TutorialDetailActivity.class);
			intent.putExtra("tutorial", tutorial);
			getContext().startActivity(intent);
		}
	};

	class SearchResultAdapter extends BaseAdapter {

		private List<TutorialInfo> tutorialsResult;

		public SearchResultAdapter(List<TutorialInfo> tutorials) {
			this.tutorialsResult = tutorials;
		}

		@Override
		public int getCount() {
			return tutorialsResult.size();
		}

		@Override
		public Object getItem(int position) {
			return tutorialsResult.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			TutorialInfo tutorial = tutorialsResult.get(position);
			View view = inflate(getContext(),
					R.layout.tutorial_search_result_item, null);
			TextView txtName = (TextView) view.findViewById(R.id.tutorial_name);
			txtName.setText(tutorial.getTitle());
			return view;
		}
	}

	class SearchTask extends AsyncTask<String, Integer, List<TutorialInfo>> {

		@Override
		protected List<TutorialInfo> doInBackground(String... params) {
			String keyword = params[0];
			return TutorialProvider.getInstance().search(keyword, 0);
		}

		@Override
		protected void onPostExecute(List<TutorialInfo> result) {
			super.onPostExecute(result);
			if (result != null)
				onSearchSuccess(result);
			else
				onSearchFail();
		}

	}
}
